package com.koron.plan.web.repairplan.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.koron.bean.base.Response;
import com.koron.bean.query.OrderItem;
import com.koron.bean.query.PageQuery;
import com.koron.bean.system.staff.vo.EamUser;
import com.koron.bean.workflow.RedirectQuery;
import com.koron.bean.workflow.SubmitterParam;
import com.koron.bean.workflow.WorkflowController;
import com.koron.bean.workflow.WorkflowUser;
import com.koron.common.core.annocation.CasUser;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.common.core.interceptor.OrderByInterceptor;
import com.koron.plan.config.Constants;
import com.koron.plan.web.common.CommonUtils;
import com.koron.plan.web.maintainplan.bean.entity.MaintainPlanBean;
import com.koron.plan.web.maintainplan.bean.query.MaintainPlanQuery;
import com.koron.plan.web.maintainplan.bean.vo.MaintainPlanDetailVO;
import com.koron.plan.web.maintainplan.service.MaintainPlanService;
import com.koron.plan.web.repairplan.bean.entity.PlanPackageIssueBean;
import com.koron.plan.web.repairplan.bean.query.PlanPackageIssueQuery;
import com.koron.plan.web.repairplan.bean.vo.PlanPackageIssueVO;
import com.koron.plan.web.repairplan.filter.RepairPlanFilter;
import com.koron.plan.web.repairplan.service.PlanPackageIssueService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.ADOConnection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.List;

/**
 * @author twcao
 * @title: PlanIssueController
 * @projectName GDH_EAM_V2
 * @description: 工单计划controller
 * @date 2021/9/1511:03
 */
@Slf4j
@RestController
@Api(tags = "检修计划")
@RequestMapping("/issue")
public class PlanIssueController implements WorkflowController {

    @Autowired
    private PlanPackageIssueService issueService;

    @Autowired
    private RepairPlanFilter filter;

    @Autowired
    private MaintainPlanService maintainPlanService;

    @GetMapping("/getById")
    @ApiOperation("根据id查询检修计划详情")
    public Response<PlanPackageIssueVO> getById(@CasUser @ApiIgnore EamUser user, String issueId) {
        PlanPackageIssueVO vo = ADOConnection.runTask(user.getCurrDs(), issueService, "queryById", PlanPackageIssueVO.class, issueId);
        return Response.succ(vo);
    }

    @GetMapping("/issueList")
    @ApiOperation("计划列表查询")
    public Response<PageInfo<PlanPackageIssueVO>> issueList(@CasUser @ApiIgnore EamUser user, PlanPackageIssueQuery query) {
        OrderByInterceptor.setOrderBy(query.getOrders());
        PageHelper.startPage(query.getPage(), query.getPageSize());
        List<PlanPackageIssueVO> list = ADOConnection.runTask(user.getCurrDs(), issueService, "queryList", List.class, query);
        return Response.succ(new PageInfo<>(list));
    }

    @PostMapping("/saveOrUpdate")
    @ApiOperation("新增/修改检修计划(检修计划包内的计划不允许修改)")
    public Response<PlanPackageIssueVO> saveOrUpdate(@CasUser @ApiIgnore EamUser user, @RequestBody PlanPackageIssueVO vo) {
        vo = ADOConnection.runTask(user.getCurrDs(), issueService, "saveOrUpdate", PlanPackageIssueVO.class, vo);
        return Response.succ(vo);
    }


    @PostMapping("experiment/saveOrUpdate")
    @ApiOperation("新增/修改检修计划(检修计划包内的计划不允许修改)")
    public Response<MaintainPlanDetailVO> saveOrUpdateExperiment(@CasUser @ApiIgnore EamUser user, @RequestBody MaintainPlanDetailVO maintainPlanDetail) {
        CommonUtils.update(maintainPlanDetail, user);
        maintainPlanDetail.setDeptId(StringUtils.isBlank(maintainPlanDetail.getDeptId()) ? user.getOrgId() : maintainPlanDetail.getDeptId());
        maintainPlanDetail.setDeptName(StringUtils.isBlank(maintainPlanDetail.getDeptName()) ? user.getOrgName() : maintainPlanDetail.getDeptName());
        return Response.succ(ADOConnection.runTask(user.getCurrDs(), issueService, "saveOrUpdateExperiment", MaintainPlanDetailVO.class, maintainPlanDetail));
    }

    @GetMapping("experiment/issue")
    @ApiOperation("下发试验计划，生成工单")
    @ApiImplicitParam(name = "id", value = "试验计划id", required = true, dataType = "String")
    public Response<MaintainPlanDetailVO> issue(@CasUser @ApiIgnore EamUser user, @RequestParam String id) {
        return Response.succ(ADOConnection.runTask(user.getCurrDs(), issueService, "issue", MaintainPlanDetailVO.class, id));
    }

    @GetMapping("experiment/queryList")
    @ApiOperation("试验计划列表查询")
    public Response<PageInfo<MaintainPlanBean>> queryList(@CasUser @ApiIgnore EamUser user, MaintainPlanQuery bean, PageQuery pageInfo) {
        List<OrderItem> orders = pageInfo.getOrders();
        orders.stream().forEach(orderItem -> {
            orderItem.setPrefix("plan");
        });
        PageHelper.startPage(pageInfo.getPage(), pageInfo.getPageSize(), pageInfo.getOrderBy());
        // 过滤出试验计划
        if (bean.getCode() == null){
            bean.setCode(Constants.EXPERIMENT_PLAN_PREFIX);
        }
        List<MaintainPlanBean> maintainPlanBeans = ADOConnection.runTask(user.getCurrDs(), maintainPlanService, "queryList", List.class, bean);
        return Response.succ(new PageInfo<>(maintainPlanBeans));
    }


    @GetMapping("/deleteById")
    @ApiOperation("删除检修计划(检修计划包内的计划不允许删除)")
    public Response<Boolean> deleteById(@CasUser @ApiIgnore EamUser user, String issueId) {
        Boolean flag = ADOConnection.runTask(user.getCurrDs(), issueService, "deleteById", Boolean.class, issueId);
        return Response.succ(flag);
    }

    @GetMapping("/issued")
    @ApiOperation("下发计划")
    @ApiImplicitParam(name = "issueId", value = "计划id", required = true, dataType = "String")
    public Response<PlanPackageIssueBean> issued(@CasUser @ApiIgnore EamUser user, String issueId) {
        PlanPackageIssueBean bean = ADOConnection.runTask(user.getCurrDs(), issueService, "issued", PlanPackageIssueBean.class, issueId);
        return Response.succ(bean);
    }

    @PostMapping("/issueExecute")
    @ApiOperation("开始执行工单时，调用此接口")
    @ApiImplicitParam(name = "issueCode", value = "工单编号", required = true, dataType = "String")
    public Response<PlanPackageIssueBean> issueExecute(@CasUser @ApiIgnore EamUser user, String issueCode) {
        log.info("开始执行工单时，调用此接口， issueCode = {}", issueCode);
        PlanPackageIssueBean bean = ADOConnection.runTask(user.getCurrDs(), issueService, "issueStateChange", PlanPackageIssueBean.class, issueCode, Constants.REPAIR_PACKAGE_ISSUE_STATE.EXECUTE);
        return Response.succ(bean);
    }

    @PostMapping("/issueFinish")
    @ApiOperation("工单执行完成时，调用此接口")
    @ApiImplicitParam(name = "issueCode", value = "工单编号", required = true, dataType = "String")
    public Response<PlanPackageIssueBean> issueFinish(@CasUser @ApiIgnore EamUser user, String issueCode) {
        log.info("工单执行完成时，调用此接口， issueCode = {}", issueCode);
        PlanPackageIssueBean bean = ADOConnection.runTask(user.getCurrDs(), issueService, "issueStateChange", PlanPackageIssueBean.class, issueCode, Constants.REPAIR_PACKAGE_ISSUE_STATE.FINISH);
        return Response.succ(bean);
    }


    @Override
    @ApiOperation("修改业务状态, 非前端接口")
    public Response updateState(@RequestBody RedirectQuery redirectQuery) {
        log.info("workflowUpdate = {}", JSON.toJSONString(redirectQuery));
        ADOConnection.runTask(ThreadLocalContext.get().getCurrDs(), issueService, "workflowUpdate", Boolean.class, redirectQuery);
        return Response.success();
    }

    @Override
    @ApiOperation("结束时的修改方法, 非前端接口")
    public Response updateEnd(@RequestBody RedirectQuery redirectQuery) {
        log.info("updateEnd = {}", JSON.toJSONString(redirectQuery));
        PlanPackageIssueVO vo = JSON.parseObject(redirectQuery.getFormVariables(), PlanPackageIssueVO.class);
        // 流程提交完后，直接下发
        String issueId = vo.getId();
        PlanPackageIssueBean bean = ADOConnection.runTask(ThreadLocalContext.get().getCurrDs(), issueService, "issued", PlanPackageIssueBean.class, issueId);
        return Response.success();
    }

    @Override
    @ApiOperation("作废时的修改方法, 非前端接口")
    public Response updateCancel(@RequestBody RedirectQuery redirectQuery) {
        log.info("updateCancel = {}", JSON.toJSONString(redirectQuery));
        return Response.success();
    }

    /**
     * 自动过滤
     * 点击工作流提交的时候，业务需要编写此过滤器，返回过滤后的人员信息
     * @param submitterParam
     */
    @PostMapping("/{taskN}/submitter")
    public Response<List<WorkflowUser>> submitter(@PathVariable String taskN, @RequestBody SubmitterParam submitterParam) {
        log.info("检修计划设置审批人入参: {}", JSON.toJSONString(submitterParam));
        List<WorkflowUser> users = ADOConnection.runTask(ThreadLocalContext.get().getCurrDs(), filter, taskN + "Submitter", List.class, submitterParam);
        return Response.ok(users);
    }

    /**
     * 选人组件过滤
     * 点击选人组件时，业务需要编写此过滤器，返回过滤后的人员信息
     * @param submitterParam
     */
    @PostMapping("/{taskN}/handler")
    public Response<List<WorkflowUser>> handler(@PathVariable String taskN, @RequestBody SubmitterParam submitterParam) {
        log.info("检修计划选人组件过滤入参: {}", JSON.toJSONString(submitterParam));
        List<WorkflowUser> users = ADOConnection.runTask(ThreadLocalContext.get().getCurrDs(), filter,  taskN + "Handler", List.class, submitterParam);
        return Response.ok(users);
    }
}
